package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HuigeUtils;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        if (shoppingCartMapper.getByUserId(BaseContext.getCurrentId())==null || shoppingCartMapper.getByUserId(BaseContext.getCurrentId()).size()==0){
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        }
        if (addressBookMapper.getById(ordersSubmitDTO.getAddressBookId())==null){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //向Oder表插入数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setNumber(HuigeUtils.generateOrderNumber(BaseContext.getCurrentId().intValue()));
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);

        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());


        orderMapper.insert(orders);

        //重新获取该订单
        Orders byNumber = orderMapper.getByNumber(orders.getNumber());
        //生成返回数据
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderNumber(byNumber.getNumber());
        orderSubmitVO.setOrderAmount(byNumber.getAmount());
        orderSubmitVO.setOrderTime(byNumber.getOrderTime());
        orderSubmitVO.setId(byNumber.getId());

        //将目前购物车的数据放入订单细节表中
        List<ShoppingCart> list = shoppingCartMapper.list(BaseContext.getCurrentId());
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(byNumber.getId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetailMapper.insert(orderDetail);
        }
        //将购物车清空
        shoppingCartMapper.clean(BaseContext.getCurrentId());

        return orderSubmitVO;
    }


    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        log.info("来单提醒推送成功");
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.historyOrders(ordersPageQueryDTO);
        page.getResult().forEach(orderVO -> {
            String orderDishes = orderDetailMapper.findByOrderId(orderVO.getId()).toString();
            orderVO.setOrderDishes(orderDishes);
        });
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public OrderVO getById(Long id) {
        OrderVO orderVO = orderMapper.getById(id);
        return orderVO;
    }

    @Override
    public void cancelByUser(Long id) {
        Orders orders = orderMapper.getById(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orders.setPackAmount(Orders.REFUND);
        orderMapper.update(orders);
    }

    @Override
    public void repetition(Long id) {
        List<OrderDetail> orderDetails = orderDetailMapper.findByOrderId(id);
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
           ShoppingCart shoppingCart = new ShoppingCart();
           shoppingCart.setUserId(BaseContext.getCurrentId());
           shoppingCart.setDishId(orderDetail.getDishId());
           shoppingCart.setSetmealId(orderDetail.getSetmealId());
           shoppingCart.setName(orderDetail.getName());
           shoppingCart.setImage(orderDetail.getImage());
           shoppingCart.setDishFlavor(orderDetail.getDishFlavor());
           shoppingCart.setNumber(orderDetail.getNumber());
           shoppingCart.setAmount(orderDetail.getAmount());
           shoppingCart.setCreateTime(LocalDateTime.now());
           shoppingCarts.add(shoppingCart);
        }
        shoppingCartMapper.insert(shoppingCarts);
    }

    @Override
    public OrderStatisticsVO statistics() {
       OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(Orders.TO_BE_CONFIRMED);
        Page<OrderVO> orders1 = orderMapper.historyOrders(ordersPageQueryDTO); //待派送的订单
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(Integer.valueOf(orders1.getTotal()+""));
        ordersPageQueryDTO.setStatus(Orders.CONFIRMED);
        Page<OrderVO> orders2 = orderMapper.historyOrders(ordersPageQueryDTO);
        orderStatisticsVO.setConfirmed(Integer.valueOf(orders2.getTotal()+""));
        ordersPageQueryDTO.setStatus(Orders.DELIVERY_IN_PROGRESS);
        Page<OrderVO> orders3 = orderMapper.historyOrders(ordersPageQueryDTO);
        orderStatisticsVO.setDeliveryInProgress(Integer.valueOf(orders3.getTotal()+""));
        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Long id = ordersConfirmDTO.getId();
        OrderVO byId = orderMapper.getById(id);
        ordersConfirmDTO.setStatus(byId.getStatus());
        if(ordersConfirmDTO.getStatus()==Orders.TO_BE_CONFIRMED.longValue()){
            orderMapper.update(Orders.builder().id(id).status(Orders.CONFIRMED).build());
        }
        if(ordersConfirmDTO.getStatus()!=Orders.TO_BE_CONFIRMED.longValue()){
            throw new OrderBusinessException("订单状态异常");

        }
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Long id = ordersRejectionDTO.getId();
        OrderVO byId = orderMapper.getById(id);
        if (byId.getStatus()!=Orders.TO_BE_CONFIRMED.longValue()){
            throw new OrderBusinessException("订单状态异常");
        }
        orderMapper.update(Orders.builder().id(id).status(7).rejectionReason(ordersRejectionDTO.getRejectionReason()).cancelReason(ordersRejectionDTO.getRejectionReason()).cancelTime(LocalDateTime.now()).build());
    }

    @Override
    public void cancelByAdmin(OrdersCancelDTO ordersCancelDTO) {
        Long id = ordersCancelDTO.getId();
        OrderVO byId = orderMapper.getById(id);
        orderMapper.update(Orders.builder().id(id).status(Orders.CANCELLED).cancelReason(ordersCancelDTO.getCancelReason()).cancelTime(LocalDateTime.now()).build());
    }

    @Override
    public void delivery(Long id) {
        orderMapper.update(Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build());
    }

    @Override
    public void complete(Long id) {
        orderMapper.update(Orders.builder().id(id).status(Orders.COMPLETED).deliveryTime(LocalDateTime.now()).build());
    }

    @Override
    public void reminder(Long id) {
        Map map = new HashMap();
        map.put("type", 2);//消息类型，2表示催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orderMapper.getById(id).getNumber());

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        log.info("催单提醒推送成功");
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

}
